package xyz.zhouxf.rpc.factory;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例工厂
 * @author zhouxf
 * @date 2022/9/26
 */
public class SingletonFactory {

    private static final ConcurrentHashMap<Class<?>, Object> SINGLETONS = new ConcurrentHashMap<>();

    private SingletonFactory() {

    }

    public static <T> T getInstance(Class<T> clazz) {
        Object instance = SINGLETONS.get(clazz);
        if(!SINGLETONS.containsKey(clazz)) {
            synchronized (clazz) {
                if(!SINGLETONS.containsKey(clazz)) {
                    try {
                        instance = clazz.newInstance();
                        SINGLETONS.put(clazz, instance);
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }
        }

        return clazz.cast(instance);
    }
}
